package top.cluski.tokendemo.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.cluski.tokendemo.domain.LoginUser;
import top.cluski.tokendemo.utils.RedisUtil;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = httpServletRequest.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            // 这里必须要return，防止调用回来之后走后面的代码
            return;
        }

        // 解析token
        JWT jwt = JWTUtil.parseToken(token);
        Object userId = jwt.getPayload("uid");
        if (Objects.isNull(userId)) {
            throw new RuntimeException("解析token失败");
        }

        // 从Redis中获取用户信息
        LoginUser loginUser = redisUtil.getCacheObject("login:" + String.valueOf(userId));
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("Redis获取用户信息失败");
        }

        // 存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
